import { PropType, defineComponent, inject, onMounted, ref, watchEffect } from "vue";

export default defineComponent({
    name: "Cell",
    props: {
        type: {type: String as PropType<'month'|'year'>, default: undefined},
        value: {type: [Number, String], default: undefined},
        data: {type: Object, default: undefined},
        day: {type: Date, default: undefined}
    },
    emits: ['select'],
    setup (props, {emit}) {
        const ctx: any = inject('CMDatepickerContext', null);
        const onClick = (num: number, disabled: boolean) => {
            if (disabled) {
                return;
            }
            emit('select', props.type, num);
        };
        const wrap = ref();

        onMounted(() => {
            watchEffect(() => {
                const visible = ctx.visible.value;
                const value = props.value;
                if (wrap.value && visible) {
                    const start = props.data[0];
                    const v: any = value ? value : (props.type === 'year' ? new Date().getFullYear() : (new Date().getMonth() + 1));
                    wrap.value.scrollTop = 26 * (v - start);
                }
            });
        });

        return () => <div class="cm-month-picker-cell" ref={wrap}>
            <ul>
                {
                    props.data.map((num: number) => {
                        const disabled = () => {
                            let dis = false;
                            const d = new Date(props.day);
                            if (props.type === 'year') {
                                // 年份必须使用那年的1月1号进行比较
                                // 要不然年份小于禁用年份月份大于禁用月份时 年份会被禁用
                                d.setFullYear(num);
                                d.setMonth(1);
                                d.setDate(1);
                                dis = ctx && ctx.disabledDate && ctx.disabledDate(d);
                            }
                            if (props.type === 'month') {
                                d.setMonth(num - 1);
                                dis = ctx && ctx.disabledDate && ctx.disabledDate(d);
                            }
                            return dis;
                        };
                        const classList = () => ({
                            'cm-month-picker-item': true,
                            'cm-month-picker-item-active': props.value === num,
                            'cm-month-picker-item-disabled': disabled()
                        });
                        return <li class={classList()} onClick={() => {
                            onClick(num, disabled());
                        }}>{num}</li>;
                    })
                }
            </ul>
        </div>;
    }
});
